package day27;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server2 {
    public static void main(String[] args) throws IOException {
        //通过Socket结合多线程  读写数据
        ServerSocket server = new ServerSocket(9999);
        while (true) {
            Socket client = server.accept();
            System.out.println(client.getInetAddress()+"连接成功");
            //每个客户端去连接服务端  client都是不同的  读写数据也不同
            //所以我就需要线程  每个客户端通过一个线程来负责当前客户端  数据读写
            new Server2Thread(client).start();
        }
    }
}

class Server2Thread extends Thread {
    Socket client;
    public Server2Thread(Socket client) {
        this.client = client;
    }
    public void run(){
        //读取当前客户端给我写的数据
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            while (true){
                String s = in.readLine();
                System.out.println(client.getInetAddress()+":"+s);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
